/*
 * Copyright (C) 2013 Ted Kosan
 * 
 * This file is part of MathPiper Exercise.
 * 
 * Foobar is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * Foobar is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/

package org.mathpiper.ui.gui.android;

import java.util.HashSet;
import java.util.Iterator;

import android.app.Activity;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceManager;

public class MultiSelectListPreferenceHandler implements OnPreferenceChangeListener {
    
    private String sharedPreferenceKey;
    
    private Activity activity;
    
    private String allListItems;
    
    public MultiSelectListPreferenceHandler(String keyName, String allListItems, Activity activity)
    {
	this.sharedPreferenceKey = keyName;
	this.allListItems = allListItems;
	this.activity = activity;
    }

    public boolean onPreferenceChange(Preference preference, Object o) {
	HashSet hashSet = (HashSet) o;
	Iterator stringIterator = hashSet.iterator();

	StringBuilder prefStringBuilder = new StringBuilder();;

	while (stringIterator.hasNext()) {
	    
	    String prefString = (String) stringIterator.next();
	    
	    if (prefString == null)
		continue;

	    prefStringBuilder.append(prefString);

	}

	PreferenceManager
	        .getDefaultSharedPreferences(activity)
	        .edit()
	        .putString(sharedPreferenceKey, allListItems + ":" + prefStringBuilder.toString())
	        .commit(); 

	return true;
    }

    public String getSharedPreferenceKey() {
        return sharedPreferenceKey;
    }

    public void setSharedPreferenceKey(String sharedPreferenceKey) {
        this.sharedPreferenceKey = sharedPreferenceKey;
    }
    
    

}
